package com.woniuxy.project115.kaer.tenant.consumer;

import cn.hutool.json.JSONUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.woniuxy.project115.kaer.tenant.entity.OrderLog;
import com.woniuxy.project115.kaer.tenant.entity.ServiceOrder;
import com.woniuxy.project115.kaer.tenant.mapper.OrderLogMapper;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceOrderMapper;
import com.woniuxy.project115.kaer.tenant.util.Data;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author HuH
 * @version 1.0
 * @CreatTime 2025-02-23 19:05
 * @description
 */
@Component
public class CheckOrderConsumer {
    @Resource
    private AlipayClient alipayClient;

    @Resource
    private ServiceOrderMapper serviceOrderMapper;

    @Resource
    private OrderLogMapper orderLogMapper;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @RabbitListener( bindings =
        @QueueBinding(
                value = @Queue(name = "check_order_queue"),
                exchange = @Exchange(name = "delay_ex", type = "direct"),
                key = "check_order"
        )
    )
    @RabbitHandler
    public void checkOrder(String serviceOrderNum) throws Exception {
        RLock lock = redissonClient.getFairLock(serviceOrderNum);
        try {
            lock.lock();
            ServiceOrder serviceOrder = serviceOrderMapper.selectById(serviceOrderNum);
            if (serviceOrder.getPayState() == Data.PAY_STATE_PAYED) {//如果状态已经更改过了直接返回
                return;
            }
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + serviceOrderNum + "\"}");
            String result = alipayClient.execute(alipayRequest).getBody();
            System.out.println("=============补偿机制，检查订单支付情况=============");
            System.out.println(result);
            String orderInfo= JSONUtil.parseObj(result).get("alipay_trade_query_response").toString();
            String payCode=JSONUtil.parseObj(orderInfo).get("code").toString();
            if("10000".equals(payCode)){
                String tradeStatus = JSONUtil.parseObj(orderInfo).get("trade_status").toString();
                if("TRADE_SUCCESS".equals(tradeStatus)){
                    String time = JSONUtil.parseObj(orderInfo).get("send_pay_date").toString();
                    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                    LocalDateTime payTime = LocalDateTime.parse(time, fmt);
                    //用户已经完成支付

                    serviceOrder.setPayState(Data.PAY_STATE_PAYED)
                            .setPayTime(payTime);
                    if (serviceOrder.getState() == Data.SERVICE_ORDER_WAIT_PAYMENT) {//如果此时订单状态为待支付
                        serviceOrder.setState(Data.SERVICE_ORDER_WAIT_EVALUATE);
                        // 将订单号放入延迟队列中 到期自动好评
                        rabbitTemplate.convertAndSend("", "delay_evaluate_order_queue", serviceOrderNum);
                    }
                    serviceOrderMapper.updateById(serviceOrder);

                    //更新订单操作日志
                    orderLogMapper.insert(
                            new OrderLog()
                                    .setOperator("用户")
                                    .setServiceOrderNum(serviceOrderNum)
                                    .setOperateTime(serviceOrder.getPayTime())
                                    .setOperateType("用户支付成功")
                    );
                }
            }
            //未支付成功,通过websocket通知用户
        } finally {
            //释放锁
            lock.unlock();
        }

    }
}

